import axios from 'axios'

/**
 * @returns 生成带有时间戳的随机uuid
 */
function generateTimestampedUUID() {
  // 获取当前时间的时间戳（毫秒）
  const timestamp = Date.now()
  // 生成UUID v4
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = Math.random() * 16 | 0
    let v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  })

  // 将时间戳和UUID拼接起来
  return `${timestamp.toString(16)}-${uuid}`;
}

var apiURL = 'http://tdg7b4.natappfree.cc' // 'http://localhost:8088',

/**
 * 用户信息页
 */
var User = {
  Id: -1,
  Token: '',
  Username: '',
  Nickname: '',
  Email: '',
  User_pic: '',
  CreateDate: '',
  UpdateDate: '',
  LatestPage: '',
  addressId: '', // 默认收货地址
  /**
   * @param {String} psw 待检查密码
   * @param {String} con 确认密码
   * @returns 返回布尔值与相应的信息
   */
  checkPassword: function(psw, con) {
    if(psw.length < 8) {
      return [false, '密码长度不得小于8位']
    } else if (psw.length > 24) {
      return [false, '密码长度不得大于24位']
    } else if (/[^0-9a-zA-Z.*-_#]/.test(psw)) {
      return [false, '密码中不得包含除字母、数字、点号"."、星号"*"、井号"#"、短横线"-"、下划线"_"以外的字符']
    } else if(psw !== con){
      return [false, '两次输入密码不一致']
    } else return [true, '符合']
  },
  /**
   * 使用令牌Token向服务器获取用户的详细信息，并存入全局数据中
   */
  saveInfo: async function() {
    localStorage.setItem('UserJSON', JSON.stringify(User))
  },
  getInfo: function() {
    return axios({
      method: 'get',
      url: apiURL + '/User/UserInfo',
      headers: {
        'Authorization': User.Token
      }
    })
      .then((res) => {
        console.log(res.data)
        if(res.data.code === 0){
          let info = res.data.data
          User.Id = info.id
          User.Username = info.username
          User.Nickname = info.Nickname
          User.Email = info.Email
          if(info.userPic === null) {
            User.User_pic = ''
          } else {
            User.User_pic = info.userPic
          }
          User.CreateDate = info.createTime
          User.UpdateDate = info.updateTime
          localStorage.setItem('UserJSON', JSON.stringify(User))
        } else {
          window.alert(res.data.message)
        }
      })
      .catch((error) => {
        console.log(error)
        console.log('查询用户详情出错了')
      })
  },
  /**
   * 从sessionStorage中加载数据
   */
  loadInfo: () => {
    let userJSON = localStorage.getItem('UserJSON')
    console.log('tryLoadInfo', userJSON)
    if(userJSON !== null) {
      let info = JSON.parse(userJSON)
      // console.log(info)
      User.Token = info.Token
      User.Id = info.Id
      User.Username = info.Username
      User.Nickname = info.Nickname
      User.Email = info.Email
      User.User_pic = info.User_pic
      User.CreateDate = info.CreateDate
      User.UpdateDate = info.UpdateDate
      console.log(User)
    } else {
      User.Username = ''
      User.Token = ''
    }
  }
}

export default{
  User,
  apiURL: 'http://tdg7b4.natappfree.cc', // 'http://localhost:8088',
  generateTimestampedUUID
}
